package binary

import kotlin.experimental.and

/**
 *@author haypo
 *@since 2021/7/20
 */
class LEB128 {
    // https://en.wikipedia.org/wiki/LEB128#Decode_unsigned_integer
    companion object {

    }
}

fun decodeVarUint(data:ByteArray, size: Int): Pair<ULong, Int> {
    var result = 0UL;
    for (i in data.indices) {
        val b = data[i];
        if (i == size / 7) {
            if (!b.and(0b10000000.toByte()).equals(0)) {
                throw ErrIntTooLong;
            }

            if (b.toInt().shr(size - i * 7) > 0) {
                throw ErrIntTooLarge;
            }
        }
        result = result.or(b.toULong().and(127u).shl(i * 7))
        if (b.and(0b10000000.toByte()).equals(0)) {
            return Pair(result, i + 1);
        }
    }
    throw ErrUnexpectedEnd
}